Flutter / GetX Steps / Step10: Screen - file uploading
File Uploading
-
Steps
1. pubspec.yaml
dependencies: get: ^4.6.1 http: ^1.1.0 dio: ^5.4.3 cached_network_image: ^3.3.1 image_picker: ^1.0.8 flutter_svg: ^2.0.10 get_storage: ^2.1.1 cupertino_icons: ^1.0.2 assets: - assets/logo.png - assets/icons/ 2. Service
lib/services/service.dart
import 'package:dio/dio.dart'; import 'package:get_storage/get_storage.dart'; class ImageService{ static Future uploadFile(filePath) async { //jwt authentication token var authToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InNhbTEyM0BnbWFpbC5jb20iLCJzdWIiOiI2MDViOTgxZDRkOTk4YjMxMjRhODEyMDQiLCJyb2xlIjoiY3VzdG9tZXIiLCJpYXQiOjE2MTgyMzQ4NjUsImV4cCI6MTYxODMyMTI2NX0.lYUfZ20TlFZZQO_1JKZbKYZublPRoejqnmxKOAM9CN0'; //user im use to upload image //Note: this authToken and user id parameter will depend on my backend api structure //in your case it can be only auth token var _userId = '605b981d4d998b3124a81204'; try { FormData formData = new FormData.fromMap({ "image": await MultipartFile.fromFile(filePath, filename: "dp")}); Response response = await Dio().put( "https://appointella-api.herokuapp.com/customer/$_userId", data: formData, options: Options( headers: { 'Authorization': 'Bearer $authToken', } ) ); return response; }on DioError catch (e) { return e.response; } catch(e){ } } } 3. in controller
import 'package:get/get.dart'; import 'package:image_picker/image_picker.dart'; import 'package:flutter/cupertino.dart'; import 'package:vera/services/service.dart'; class HomeController extends GetxController { var isLoading = false.obs; var imageURL = ''; void uploadImage(ImageSource imageSource) async { try { final pickedFile = await ImagePicker().pickImage(source: imageSource); isLoading(true); if (pickedFile != null) { var response = await ImageService.uploadFile(pickedFile.path); if (response.statusCode == 200) { //get image url from api response imageURL = response.data['user']['image']; Get.snackbar('Success', 'Image uploaded successfully', margin: EdgeInsets.only(top: 5,left: 10,right: 10)); } else if (response.statusCode == 401) { Get.offAllNamed('/sign_up'); } else { Get.snackbar('Failed', 'Error Code: ${response.statusCode}', margin: EdgeInsets.only(top: 5,left: 10,right: 10)); } } else { Get.snackbar('Failed', 'Image not selected', margin: EdgeInsets.only(top: 5,left: 10,right: 10)); } } finally { isLoading(false); } } } 4. in view
import 'package:flutter/material.dart'; import 'package:vera/controllers/home_controller.dart'; import 'package:get/get.dart'; import 'package:vera/widgets/drawer.dart'; import 'package:vera/widgets/bottom_nav.dart'; import 'package:flutter_svg/svg.dart'; import 'package:image_picker/image_picker.dart'; import 'package:cached_network_image/cached_network_image.dart'; class HomePage extends StatelessWidget { final HomeController profilerController = Get.put(HomeController()); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Container( decoration: BoxDecoration( boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.3), blurRadius: 40, ), ], ), child: SizedBox( height: 115, width: 115, child: Stack( fit: StackFit.expand, children: [ Obx((){ if(profilerController.isLoading.value){ return CircleAvatar( backgroundImage: AssetImage('assets/icons/no_user.jpg'), child: Center( child: CircularProgressIndicator( backgroundColor: Colors.white, )), ); } else { if(profilerController.imageURL.length != 0){ return CachedNetworkImage( imageUrl: profilerController.imageURL, fit: BoxFit.cover, imageBuilder: (context, imageProvider) => CircleAvatar( backgroundColor: Colors.white, backgroundImage: imageProvider, ), placeholder: (context, url) => CircleAvatar( backgroundImage: AssetImage('assets/icons/no_user.jpg'), child: Center( child: CircularProgressIndicator( backgroundColor: Colors.white, )), ), errorWidget: (context, url, error) => Icon(Icons.error), ); } else { return CircleAvatar( backgroundImage: AssetImage('assets/icons/no_user.jpg'), ); } } }), Positioned( right: -16, bottom: 0, child: SizedBox( height: 46, width: 46, child: TextButton( onPressed: () { Get.bottomSheet( Container( decoration: BoxDecoration( color: Colors.white, borderRadius: const BorderRadius.only( topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)), ), child: Wrap( alignment: WrapAlignment.end, crossAxisAlignment: WrapCrossAlignment.end, children: [ ListTile( leading: Icon(Icons.camera), title: Text('Camera'), onTap: () { Get.back(); profilerController.uploadImage(ImageSource.camera); }, ), ListTile( leading: Icon(Icons.image), title: Text('Gallery'), onTap: () { Get.back(); profilerController .uploadImage(ImageSource.gallery); }, ), ], ), ), ); }, child: SvgPicture.asset("assets/icons/Camera Icon.svg"), ), ), ) ], ), ), ), ) ); } }